package com.ptswitch.material.dao.impl;

import java.util.List;

import org.hxzon.project.SpringJdbcDao;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.ptswitch.material.model.common.Uzer;

@Repository
public class UserDao extends SpringJdbcDao {
    private static final RowMapper<Uzer> userMapper = buildBeanRowMapper(Uzer.class);
    private static final String SelectCommon = "select id,username,password,realname,department,adminGrade,email,uzerRoles,createTime,updateTime ";
    private static final String FromTable = " from uzer ";
    private static final String DefaultOrderBy = " order by username ";

    public void save(Uzer user) {
        String fullSql = null;
        if (user.getId() == null) {
            user.setId(super.buildUuid());
            fullSql = "insert into uzer(id,username,password,realname,"//
                    + "email,adminGrade,department,uzerRoles,createTime,updateTime)"//
                    + " values(:id,:username,:password,:realname,"//
                    + ":email,:adminGrade,:department,:uzerRoles,:createTime,:updateTime)";
        } else {
            fullSql = "update uzer set "//
                    + " username=:username,realname=:realname"//
                    + " ,email=:email,adminGrade=:adminGrade,department=:department "//
                    + " ,uzerRoles=:uzerRoles,updateTime=:updateTime"//
                    + " where id=:id";
        }
        super.execute(fullSql, buildBeanParams(user));
    }

    public void delete(Uzer user) {
        String deleteSql = "delete uzer where id=:id";
        super.execute(deleteSql, buildMapParams("id", user.getId()));
    }

    public Uzer findById(String id) {
        String findSql = SelectCommon + FromTable + " where id=:id";
        return super.queryOne(findSql, buildMapParams("id", id), userMapper);
    }

    public Uzer findByUsername(String username) {
        String findSql = SelectCommon + FromTable + " where username=:username " + DefaultOrderBy;
        return super.queryOne(findSql, buildMapParams("username", username), userMapper);
    }

    public List<Uzer> findByDepartment(int department) {
        String findSql = SelectCommon + FromTable + " where department=:department " + DefaultOrderBy;
        return super.queryList(findSql, buildMapParams("department", department), userMapper);
    }

    public List<Uzer> findAll() {
        String findSql = SelectCommon + FromTable + DefaultOrderBy;
        return super.queryList(findSql, buildMapParams(), userMapper);
    }

    public long countAll() {
        String findSql = "select count(id) " + FromTable;
        return super.count(findSql, buildMapParams());
    }
}
